/*
 * 菜单显示控制
 */
let columnMenu;

/**
 * 获取表的字段
 * @param selector 表的选择器
 * @returns {Object[]}
 */
function getFields(selector) {
	let key = "mhxysy:fields:" + selector;
	let item = localStorage.getItem(key);

	let fields = [];

	if (item == null) {
		let datagrid = $(selector);
		let columnFields = datagrid.datagrid("getColumnFields");

		for (let i = 0; i < columnFields.length; i++) {
			let item = columnFields[i];

			fields.push({
				name: item,
				selected: true
			});
		}

		setFields(selector, fields); // 设置缓存
	} else {
		fields = JSON.parse(item);
	}

	return fields;
}

/**
 * 设置表的字段
 * @param selector 表的选择器
 * @param fields 表的字段
 */
function setFields(selector, fields) {
	let key = "mhxysy:fields:" + selector;

	localStorage.setItem(key, JSON.stringify(fields));
}

/**
 * 勾选表的字段
 * @param selector 表的选择器
 * @param name 表的字段
 * @param selected 勾选-true;取消勾选-false
 */
function selectFields(selector, name, selected) {
	let key = "mhxysy:fields:" + selector;
	let item = localStorage.getItem(key);

	if (item != null) {
		let fields = JSON.parse(item);

		fields = fields.map(function (item) {
			if (item.name === name) {
				item.selected = selected;
			}

			return item;
		});

		setFields(selector, fields); // 更新缓存
	}
}

/**
 * 创建表格的右键菜单
 * @param selector 表格dom对象的选择器
 */
function createColumnMenu(selector) {
	let datagrid = $(selector);
	let checked = "icon-checked"; // icon-ok
	let unchecked = "icon-unchecked";

	columnMenu = $("<div/>").appendTo("body");

	columnMenu.menu({
		onClick: function(item) {
			let name = item.name;

			if (item.iconCls === checked) {
				datagrid.datagrid("hideColumn", name);

				columnMenu.menu("setIcon", {
					target: item.target,
					iconCls: unchecked
				});

				selectFields(selector, name, false);
			} else {
				datagrid.datagrid("showColumn", name);

				columnMenu.menu("setIcon", {
					target: item.target,
					iconCls: checked
				});

				selectFields(selector, name, true);
			}

			datagrid.datagrid("reload");
			datagrid.datagrid("fitColumns");
		}
	});

	let fields = getFields(selector);

	if (fields.length > 0) {
		for (let i = 0; i < fields.length; i++) {
			let field = fields[i];

			let name = field.name;
			let selected = field.selected;

			let column = datagrid.datagrid("getColumnOption", name);

			columnMenu.menu("appendItem", {
				name: name,
				text: column.title,
				iconCls: selected ? checked : unchecked
			});
		}
	}
}